package cn.edu.dlut.port.isp.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.dlut.smartport.utils.DBUtil;

@Controller
public class FileController {
	DBUtil db;

	@PostMapping("/load")
	public ModelAndView fileload(MultipartFile file,
			HttpServletRequest request, HttpSession session) {
		db = new DBUtil();
		db.init();
		// 获取session中id
		Object id = session.getAttribute("id");
		DBUtil db;
		db = new DBUtil();
		db.init();
		// 查询student表对应id，区别是哪位学生上传
		String SQL = "SELECT sname FROM students WHERE sid=" + id + "";
		List nameList = db.getList(SQL);
		// 提取上传者名字
		String name = (String) ((Map) nameList.get(0)).get("sname");
		// 获取文件名称
		String fileName = file.getOriginalFilename();
		// 设置上传路径
		String path = "D:/smartport上传文件/" + name + "/";

		// 文件上传
		File f = new File(path);

		// 判断路径是否存在，不存在则创建
		if (!f.exists()) {
			f.mkdirs();
		}
		// 判断上传文件是否为空
		if (!file.isEmpty()) {
			try {
				FileOutputStream fos = new FileOutputStream(path + fileName);
				InputStream in = file.getInputStream();
				int a = 0;
				while ((a = in.read()) != -1) {
					fos.write(a);
				}
				in.close();
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 将文件参数传给数据库
		String fileSQL = "INSERT INTO file_info(file_name,file_url,sid)VALUES('"
				+ fileName + "','" + path + "','" + id + "')";
		int fileResult = db.update(fileSQL);
		ModelAndView mav = new ModelAndView("teach/teach1");
		return mav;
	}
	
 	@ResponseBody
    @RequestMapping("/downFile")
    public void download(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取文件的绝对路径名称
        String path = "D:/devEnv8/workspace/smartport/src/main/resources/templates/downLoad/报告模板.docx";
        //转码，中文文件名要使用URLEncoder.encode方法进行编码
        String filename = URLEncoder.encode("报告模板.docx","UTF-8");
        //设置文件下载头
        resp.addHeader("Content-Disposition", "attachment;filename=" + filename);
        //设置文件ContentType类型，这样设置会自动判断下载文件类型
        resp.setContentType("multipart/form-data");
        //读取要下载的文件，保存到文件输入流
        FileInputStream in = new FileInputStream(path);
        // 创建输出流
        OutputStream out = resp.getOutputStream();
        // 创建缓冲区 及 缓冲区的大小设置
        byte[] buf = new byte[1024];
        int len = 0;
        //循环将输入流中的内容读取到缓冲区当中
        while((len = in.read(buf)) > 0){
            out.write(buf, 0, len);
        }
        //关闭文件输入流
        in.close();
        // 关闭输出流
        out.close();
    }

}
